package org.goodsl.deploymap

/**
 * Created with IntelliJ IDEA.
 * User: Simon Xiao
 * Date: 12-12-19
 * Time: 上午9:59
 * Copyright goodsl.org 2012~2020
 */
class Host extends SysElement{

    ArrayList<DeployedService> hostService = new ArrayList<DeployedService>()

    boolean isStorage = false
    boolean isVm = false
    Env env

    Deploy deploy = new Deploy(host: this)

    public boolean getIsPublicAccess(){

        for (DeployedService ds in hostService){
           if (ds.service.isPublicAccess)
               return true
        }
        return false;

    }
    public int getServiceCount(){
        return hostService.size()
    }


    void deploy(Closure cl){

        cl.delegate = deploy
        cl.resolveStrategy = Closure.DELEGATE_FIRST
        cl()
    }


    void storage(boolean isStorage){
        this.isStorage = isStorage
    }

    void vm(boolean isVm){
        this.isVm = isVm
    }


    def propertyMissing(String name){
        if (name == "storage")
            this.isStorage = true
        else if (name == "vm")
            this.isVm = true
    }


}



class Deploy {
    Host host

    def methodMissing(String servicedName, args){
        Service service = host.system.getService(servicedName)
        if (service == null) {
            System.out.println("Error :not define servie [${servicedName}] in env:[${host.env.name}] host:[${host.name}]")
            return
        }

        String deployName = ""
        long deployPort = -1

        Object[] params = (Object[])args
        if (params.length >0){
            if (params[0].class == String)
                deployName = params[0]
            else if(Number.isAssignableFrom(params[0].class))
                deployPort = (long)params[0]

        }
        if (params.length >1){
            if (params[1].class == String)
                deployName = params[1]
            else if(Number.isAssignableFrom(params[1].class))
                deployPort = (long)params[1]

        }

        DeployedService deployedService = new DeployedService(
                service: service ,
                name: deployName,
                port: deployPort
        )

        host.hostService.add(deployedService)


    }

    def propertyMissing(String servicedName){
        Service service = host.system.getService(servicedName)
        if (service == null)
            throw  new Exception("not define servie '${servicedName}' ")

        DeployedService deployedService = new DeployedService(
                service: service,
                name: ""
        )

        host.hostService.add(deployedService)

    }

}